<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>管理员管理</title>
    <link rel="stylesheet" href="../res/layui/css/layui.css">
    <style>
        .form-container {
            max-width: 600px;
            margin: 0 auto;
        }
        .form-title {
            font-size: 18px;
            margin-bottom: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
<div class="layui-fluid">
    <div class="form-container">
        <div class="form-title" id="pageTitle">管理员添加</div>
        <form class="layui-form layui-form-pane" id="adminForm">
            <input type="hidden" name="id" id="adminId">
            
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" id="username" value="" 
                           lay-verify="required|username" 
                           lay-vertype="tips" 
                           lay-reqtext="请输入用户名" 
                           placeholder="请输入用户名" 
                           autocomplete="off" 
                           class="layui-input">
                </div>
            </div>
            
            <div class="layui-form-item" id="passwordContainer">
                <label class="layui-form-label">密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" id="password" value="" 
                           lay-verify="password" 
                           lay-vertype="tips" 
                           placeholder="请输入密码（编辑时不填则保持原密码）" 
                           autocomplete="off" 
                           class="layui-input" 
                           lay-affix="eye">
                </div>
            </div>
            
            <div class="layui-form-item" id="passwordConfirmContainer">
                <label class="layui-form-label">确认密码</label>
                <div class="layui-input-block">
                    <input type="password" name="passwordConfirm" value="" 
                           lay-verify="passwordConfirm" 
                           lay-vertype="tips" 
                           placeholder="请再次输入密码" 
                           autocomplete="off" 
                           class="layui-input" 
                           lay-affix="eye">
                </div>
            </div>
            
            <div class="layui-form-item" id="statusContainer">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <input type="radio" name="status" value="1" title="启用" checked>
                    <input type="radio" name="status" value="0" title="禁用">
                </div>
            </div>
            
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="submitAdmin">保存</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="../res/layui/layui.js"></script>
<script>
    layui.use(['form', 'layer', 'jquery'], function() {
        // 获取form对象
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;
        
        // 获取URL中的ID参数，判断是添加还是编辑模式
        var urlParams = new URLSearchParams(window.location.search);
        var adminId = urlParams.get('id');
        
        // 如果存在ID，则为编辑模式
        if (adminId) {
            $('#pageTitle').text('管理员编辑');
            $('#password').attr('placeholder', '请输入密码（不填则保持原密码）');
            $('#password').removeAttr('lay-verify');
            $('#passwordConfirmContainer').hide();
            
            // 根据ID获取管理员信息
            $.get('/admin/details?id=' + adminId, function(R) {
                if (R.code === 200) {
                    var admin = R.data;
                    $('#adminId').val(admin.id);
                    $('#username').val(admin.username);
                    // 回显状态
                    if (admin.status === 0) {
                        $(":radio[name='status'][value='0']").attr('checked', true);
                    }
                    form.render('radio');
                } else {
                    layer.msg(R.message || '获取管理员信息失败', {icon: 5});
                }
            }, 'json');
        }
        
        // 自定义验证规则
        form.verify({
            username: function(value) {
                if (value.length < 3) {
                    return '用户名至少得3个字符';
                }
            },
            password: [
                /^[\S]{6,12}$/,
                '密码必须6到12位，且不能出现空格'
            ],
            passwordConfirm: function(value) {
                var password = $(".layui-form-item input[name='password']").val();
                if(value !== password) {
                    return '两次密码输入不一致';
                }
            }
        });

        // 提交事件
        form.on('submit(submitAdmin)', function(data) {
            var field = data.field; // 获取表单字段值
            
            // 如果没有输入新密码且是编辑模式，则移除密码字段
            if (adminId && (!field.password || field.password.trim() === '')) {
                delete field.password;
            }
            
            // 移除确认密码字段
            delete field.passwordConfirm;
            
            // 准备请求URL和类型
            var url = adminId ? '/admin/update' : '/admin/add';
            var type = adminId ? 'PUT' : 'POST';
            
            // 发送请求
            $.ajax({
                url: url,
                type: type,
                contentType: 'application/json',
                data: JSON.stringify(field),
                success: function(R) {
                    if (R.code === 200) {
                        layer.msg(R.message || (adminId ? '更新成功' : '添加成功'), {icon: 6});
                        // 延迟跳转回列表页面
                        setTimeout(function() {
                            window.parent.document.getElementById('iframe').src = 'html/admin-list.html';
                        }, 1000);
                    } else {
                        layer.msg(R.message || (adminId ? '更新失败' : '添加失败'), {icon: 5});
                    }
                },
                error: function() {
                    layer.msg('网络错误，请稍后重试', {icon: 5});
                }
            });
            
            return false; // 阻止默认 form 跳转
        });
        
        // 取消按钮点击事件
        $('#cancelBtn').on('click', function() {
            // 返回列表页面
            window.parent.document.getElementById('iframe').src = 'html/admin-list.html';
        });
    });
</script>
</body>
</html>